import { Injectable } from '@nestjs/common';
import { ResultData, SUCCESS_CODE } from 'src/common/utils/result';
import { UserService } from '../system/user/user.service';
import { LoginlogService } from '../monitor/loginlog/loginlog.service';
import { AxiosService } from 'src/module/common/axios/axios.service';
import { AccountLoginDto, LoginDto, MobileLoginDto, RegisterDto } from './dto/index';
import { MenuService } from '../system/menu/menu.service';
import { ClientInfoDto } from 'src/common/decorators/common.decorator';
import SmsSender from '../main/smsSender';
import { ConfigService } from '@nestjs/config';
import { CacheEnum } from '../../common/enum'; // 导入 ConfigService
import { RedisService } from 'src/module/common/redis/redis.service';
import { UserDto } from '../system/user/user.decorator';

@Injectable()
export class MainService {
  constructor(
    private readonly userService: UserService,
    private readonly loginlogService: LoginlogService,
    private readonly axiosService: AxiosService,
    private readonly menuService: MenuService,
    private readonly configService: ConfigService, // 注入 ConfigService
    private readonly redisService: RedisService,
  ) {}

  /**
   * 登陆
   * @param user
   * @returns
   */
  async login(user: LoginDto, clientInfo: ClientInfoDto) {
    const loginLog = {
      ...clientInfo,
      status: '0',
      msg: '',
    };
    try {
      const loginLocation = await this.axiosService.getIpAddress(clientInfo.ipaddr);
      loginLog.loginLocation = loginLocation;
    } catch (error) {}
    const loginRes = await this.userService.login(user, loginLog);
    loginLog.status = loginRes.code === SUCCESS_CODE ? '0' : '1';
    loginLog.msg = loginRes.msg;
    this.loginlogService.create(loginLog);
    return loginRes;
  }

  async accountLogin(user: AccountLoginDto, clientInfo: ClientInfoDto) {
    const loginLog = {
      ...clientInfo,
      status: '0',
      msg: '',
    };

    try {
      loginLog.loginLocation = await this.axiosService.getIpAddress(clientInfo.ipaddr);
    } catch (error) {}

    const loginRes = await this.userService.accountLogin(user, loginLog);
    loginLog.status = loginRes.code === SUCCESS_CODE ? '0' : '1';
    loginLog.msg = loginRes.msg;

    this.loginlogService.create(loginLog);

    return loginRes;
  }

  async mobilLogin(user: MobileLoginDto, clientInfo: ClientInfoDto) {
    const loginLog = {
      ...clientInfo,
      status: '0',
      msg: '',
    };

    try {
      loginLog.loginLocation = await this.axiosService.getIpAddress(clientInfo.ipaddr);
    } catch (error) {}

    const loginRes = await this.userService.mobilLogin(user, loginLog);
    loginLog.status = loginRes.code === SUCCESS_CODE ? '0' : '1';
    loginLog.msg = loginRes.msg;

    this.loginlogService.create(loginLog);

    return loginRes;
  }
  /**
   * 退出登陆
   * @param clientInfo
   */
  async logout(clientInfo: ClientInfoDto) {
    const loginLog = {
      ...clientInfo,
      status: '0',
      msg: '退出成功',
    };
    try {
      const loginLocation = await this.axiosService.getIpAddress(clientInfo.ipaddr);
      loginLog.loginLocation = loginLocation;
    } catch (error) {}
    this.loginlogService.create(loginLog);
    return ResultData.ok();
  }

  /**
   * 注册
   * @param user
   * @returns
   */
  async register(user: RegisterDto) {
    return await this.userService.register(user);
  }

  /**
   * 登陆记录
   */
  loginRecord() {}

  /**
   * 获取路由菜单
   */
  async getRouters(userId: number) {
    const menus = await this.menuService.getMenuListByUserId(userId);
    return ResultData.ok(menus);
  }

  async sendCode(mobile: string) {
    // 生成1000到9999之间的随机4位数验证码
    const code = Math.floor(Math.random() * 9000 + 1000).toString();

    // 将验证码保存到Redis中，并设置有效期5分钟
    await this.redisService.set(CacheEnum.CAPTCHA_CODE_KEY + mobile, code, 1000 * 60 * 5);

    // 创建短信发送器实例
    const smsSender = new SmsSender(this.configService);

    // 发送短信验证码
    const result = await smsSender.sendSms(
      mobile,
      '上海智影慧心数字科技', // 短信签名名称
      'SMS_322275475', // 短信模板CODE
      JSON.stringify({
        // 短信模板变量对应的实际值
        code: code,
      }),
    );
    return ResultData.ok(result);
  }
}
